

public class 岛屿的周长 {
    public int islandPerimeter(int[][] grid) {
           int sum=0;
           int count=0;
           for (int i=0;i<grid.length;i++){
               for (int j=0;j<grid[i].length;j++){
                   if (grid[i][j]==1) {
                       sum++;
                       //从上方开始找相邻的格子
                       if (i >= 1 && grid[i - 1][j] == 1) {
                           count++;
                       }
                       //从右方开始找相邻格子
                       if (j >= 1 && grid[i][j - 1] == 1) {
                           count++;
                       }
                   }
               }
           }
           return  sum*4-count*2;
    }
}
